<?php
    class MY_Controller extends CI_Controller
    {
        protected static $controller_title  = '';

        protected $user                     = NULL;
        protected $priv                     = array();
        protected $menu                     = NULL;
        protected $action_title             = '';

        public function __construct()
        {
            parent::__construct();

            $this->user = $this->session->userdata('admin');

            if ($this->user === FALSE) {
                $this->user = array(
                    'user_id'   => 0,
                    'role'      => 'guest',
                    'user_name' => 'Guest'
                );
            }

            $this->authentication();
        }

        protected function auth_error_handler($msg, $status_code = 500)
        {
            show_error($msg, $status_code);
        }

        protected function authentication()
        {
            if (empty($this->priv)) {
                $this->load_priv();
            }

            $handler = $this->uri->rsegment(1) . '/' . $this->uri->rsegment(2);
            $is_allow = in_array($this->uri->rsegment(1) . '/*', $this->priv) || in_array($handler, $this->priv);
            if (!$is_allow) {
                $this->auth_error_handler('你没有权限使用此功能', 403);
            }
        }

        private function load_priv()
        {
            $purview = $this->config->item('purview');
            if ($purview === FALSE) {
                log_message('error', 'config/priv.php权限配置文件取不到值');
                $this->auth_error_handler('系统文件损坏，请与管理员系统');
            }

            $role = $this->config->item('role');

            if ($role === FALSE || array_key_exists($this->user['role'], $role) === FALSE) {
                log_message('error', "不存在的角色:{$this->user['role']}，请检查config/role.php角色配置文件");
                $this->auth_error_handler('系统文件损坏，与管理员系统');
            }

            foreach ($role[$this->user['role']]['modules'] as $item) {
                $this->priv = array_merge($purview[$item], $this->priv);
            }

            if (empty($this->priv)) {
                log_message('error', '角色的功能权限为空，请检查config/role.php角色配置文件');
                $this->auth_error_handler('系统文件损坏，与管理员系统');
            }
        }
    }
